package tk.jfree.example.gridfs.api;

import io.swagger.annotations.ApiOperation;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tk.jfree.example.gridfs.service.FileService;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author Cheng.Wei
 * @date 2019/09/23 11:55
 */
@RestController
@RequestMapping("file")
public class FileController {
    @Autowired private FileService fileService;

    @ApiOperation("保存")
    @PostMapping
    public String save(MultipartFile file) throws IOException {
        return fileService.save(file).toString();
    }

    @ApiOperation("下载")
    @GetMapping("{id}")
    public ResponseEntity get(@PathVariable String id) throws IOException {
        GridFsResource gridFs = fileService.get(id);
        return  ResponseEntity.ok()
                .header("Content-Disposition", "attachment;filename=" + URLEncoder.encode(gridFs.getFilename(), "UTF-8"))
                .header("Content-Type",gridFs.getContentType())
                .body(FileCopyUtils.copyToByteArray(gridFs.getInputStream()));
    }

    @ApiOperation("删除")
    @DeleteMapping("{id}")
    public ResponseEntity delete(@PathVariable String id){
        fileService.delete(id);
        return ResponseEntity.ok().build();
    }
}
